import {getToken,setToken,removeToken} from '@/utils/auth'
import {login ,getUserInfo} from '@/api/user'
import {constantRoutes } from '@/router'
import { resetRouter } from '@/router'

const state={
    token:getToken(),
    userInfo:{},
    routes: constantRoutes // 静态路由的数组
}
const mutations={
    setToken(state,token){
      state.token = token
      setToken(token)
    },
    setUserInfo(state,userInfo){
        state.userInfo= userInfo;
    },
    //todo删除
    removeToken(state){
      state.token = null
      removeToken()
    },
    //
    setRoutes(state, newconstantRoutes){
      state.routes = [...constantRoutes,...newconstantRoutes]
    }

}
const actions={
  //登录用户
  async login(context,data){
    const token = await login(data)
    context.commit('setToken',token)
  },
  //获取用户的信息
  async getUserInfo(context){
    const userInfo = await getUserInfo()
    context.commit('setUserInfo', userInfo)
    return userInfo
  },
  //退出登录
  async logout(context){
    context.commit('removeToken')
    context.commit('setUserInfo',{})
    // 重置路由
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

